package top.wbhzx.wangpan.entity;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * 根据map自动位封装类赋值
 * @author wangbohui
 */
public class AttrUtil {

	/**
	 * 根据封装类和属性名，设置属性值
	 * @param o 封装类
	 * @param field 属性名
	 */
	public static void setAttribute(Object o,String field, Object keyWord) throws IllegalAccessException, NoSuchFieldException {
		Field f = o.getClass().getDeclaredField(field);
		f.setAccessible(true);
		f.set(o, keyWord);
	}

	/**
	 * 根据封装类和属性名，获得属性值
	 * @param o 封装类
	 * @param field 属性名
	 */
	public static String getAttribute(Object o,String field) throws NoSuchFieldException, IllegalAccessException {
	    String r;
	        Field f = o.getClass().getDeclaredField(field); 
	        f.setAccessible(true); 
	        r =  f.get(o).toString();
	    return r;
	}

	/**
	 * 使用一个map为封装类型赋值
	 * @param o 封装类
	 * @param map 属性与值的map
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 */
	public static void setAttributes(Object o, Map<String, Object> map) throws NoSuchFieldException, IllegalAccessException {
		for(Map.Entry<String,Object> entry : map.entrySet()) {
			AttrUtil.setAttribute(o, entry.getKey(), entry.getValue());
		}
	}

	private AttrUtil(){}
	
}
